<?php

namespace App\Models;

use App\Logic\Code;
use App\Logic\NowApi;
use App\Logic\Upload;
use App\Logic\point\Point;
use App\Logic\point\Message;
use App\Logic\calculate\Level;

use App\Models\MinerInfo;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Db;
use Illuminate\Support\Facades\Cache;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{

    /**
     * 绑定数据表
     * @var string
     */
    protected $table = 'order';


    public static function add($data,$user){
        $validateRule = [
            'buy_type'                          => 'required',
            'buy_num'                           => 'required',
            'pic'                               => 'required',
            'pay_type'                          => 'required',
            'note'                              => 'present',
            'account'                           => 'required',
            'name'                              => 'required',
        ];
        $errorMsg = [
            'buy_type.required'                 => '购买类型不能为空',
            'buy_num.required'                   => '购买数量不能为空',
            'pic.required'                      => '凭证不能为空',
            'pay_type.required'                   => '支付类型不能为空',
            'note.present'                   => '备注字段需要，可以为空',
            'account.required'                   => '账户不能为空',
            'name.required'                   => '姓名不能为空',
        ];


        $validator = Validator::make($data, $validateRule, $errorMsg);
        if ($validator->fails()){
            $errors = $validator->errors()->all();
            return e_msg(300001,$errors[0]);
        }

        /*
         * 1.处理图片
         * 2.整理数组
         * 1.价格
         * 3.添加
         * */

        $products = Cache::get('config_products');
        $products_arr = array_column($products,'id');
        if(in_array($data['buy_type'],$products_arr)){
            $products_arr_key = array_keys($products_arr,$data['buy_type'])[0];
            $product = $products[$products_arr_key];
        }else{
            return e_msg(300017,'产品id不存在');
        }

        $capacity = $product->capacity * $data['buy_num'];
        $unit_price = self::unit($capacity);
        $rate_info = 0;

        $all_cny = $unit_price * $capacity;
        if($data['pay_type'] === 'usdt') {

            $rate = NowApi::index();
            if($rate['status'] === 'SUCCESS'){
                $rate_info = $rate['data'];
                $usdt_price = $unit_price/$rate['data'];
                $unit_price = round($usdt_price,2);
            }else{
                return $rate;
            }
        }
        $pic = Upload::base64($data['pic']);
        if($pic['status'] === 'ERROR') {
            return $pic;
        }else{
            $pic = get_http_type().$_SERVER['HTTP_HOST'].'/uploads/orders/'.$pic['data'];
        }

        $all_price = $unit_price * $capacity;

        $insert_arr = [
            'user_name' => $user->username,
            'buy_num' => $data['buy_num'],
            'pay_type' => $data['pay_type'],
            'pay_account' => $data['account'],
            'pay_name' => $data['name'],
            'unit_price' => $unit_price,
            'all_price' => $all_price,
            'all_capacity' => $capacity,
            'all_cny' => $all_cny,
            'rate' => $rate_info,
            'product_id' => $data['buy_type'],
            'product_name' => $product->name,
            'product_capacity' => $product->capacity,
            'product_hostrate' => $product->hostrate,
            'product_token' => $product->token,
            'note' => $data['note'],
            'pic' => $pic,
        ];

        $rel = Db::table('order')->insert($insert_arr);

        if($rel){
            return s_msg('');
        }else{
            return e_msg(300006,'添加失败');
        }

    }


    //获取单价
    public static function unit($amount){

        $price = Cache::get('config_price');

        $brr = array_column($price,'amount');
        if(in_array($amount,$brr)){
            $k = array_keys($brr,$amount)[0]-1;
        }else{
            array_push($brr,$amount);
            sort($brr);
            $k = array_keys($brr,$amount)[0]-1;
        }
        $val = $price[$k];
        return $val->price;
    }


    public static function check($info)
    {

        //判断最大容量
        $time = time();
        $token = $info->product_token;
        $host = DB::table('miner_host')
        ->where('token','FIL')
        //->where('start_time','<',$time)
        ->where('end_time','>',$time)
        ->sum('hspace');
        $all_host = $host + $info->all_capacity;
        $origin = Point::curl();

        if($origin['status'] == 'ERROR'){
            return $origin;
        }else{
            if($origin['data']['code'] == 0 ){
                return e_msg(3202300,'请求您的总容量失败');
            }else{
                if($all_host>$origin['data']['data']){
                    return e_msg(3202300,'可用总容量为'.$origin['data']['data'].'已超出限额，请联系官方客服扩容');
                }
            }
        }

        //修改订单状态
        //批量添加 矿机 托管 关联用户
        //更新父节点等级

        $start_time = 1589472000; //2020-05-15 00:00:00
        if($time>$start_time){
            $start_time = strtotime(date('Y-m-d'));
        }

        $year = date('Y',$start_time)+3;
        $new_year =date('-m-d H:i:s',$start_time);
        $new_new = $year.$new_year;

        $end_time = $start_time + 1095 *86400;

        //$end_time = strtotime($new_new);



        $hostrate = $info->product_hostrate;
        $capacity = $info->product_capacity;


        $add_token = MinerInfo::add_token();

        $miner_info_insert_arr = [];


        if($capacity == 72) {

            $num = $info->buy_num;
            $first_capacity = 72;

        }else{

            $n = $info->buy_num;
            $num = ceil($n/72);
            $first_capacity = $n%72;
            if($first_capacity == 0){
                $first_capacity = 72;
            }

        }

        $m_number_res = MinerInfo::m_number($token);

        for ($i = 0; $i < $num; $i++) {

            if ($i == 0) {
                $m_number = $token . $m_number_res;
            } else {
                $m_number_res = intval($m_number_res) + 1;
                $c = str_pad($m_number_res, 3, '0', STR_PAD_LEFT);
                $m_number = $token .$c;
            }

            $m_pass = rand(100000, 999999);
            $miner_info_insert_arr[] = [
                'm_number' => $m_number,
                'm_pass' => $m_pass,
                'm_type' => 72,
                'note' => $info->product_id,
                'add_token' => $add_token,
            ];

        }

        //添加矿机
        DB::table('miner_info')->insert($miner_info_insert_arr);
        $miner_info_list = DB::table('miner_info')
            ->where('add_token', $add_token)
            ->select('mid')
            ->get();

        $miner_host_insert_arr = [];
        $miner_user_insert_arr = [];

        foreach ($miner_info_list as $k=>$v) {

            if($k == 0) {
                $hspace = $first_capacity;
            }else{
                $hspace = 72;
            }

            $miner_host_insert_arr[] = [

                'mid' => $v->mid,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'token' => $token,
                'hspace' => $hspace,
                'hostrate' => $hostrate,

            ];

            $miner_user_insert_arr[] = [

                'mid' => $v->mid,
                'user_name' => $info->user_name,

            ];
        }
        //添加托管记录和用户绑定矿机信息
        DB::table('miner_host')->insert($miner_host_insert_arr);
        DB::table('miner_user')->insert($miner_user_insert_arr);


        //更新订单状态
        self::where('id',$info->id)->update(['status' => 1,'check_time'=>date('Y-m-d H:i:s',$time)]);

        //计算父级，
        //更新父级业绩

        //计算大区和小区业绩总量
        //根据业绩总量更新等级

        $user_info = DB::table('user')->where('username',$info->user_name)->select('id','pid','path','phone','username')->first();

        Level::index($user_info,$info->all_cny,$info->all_capacity);


        Message::index($info->id);

        $config_sys = Cache::get('config_sys');
        foreach($config_sys as $val){
            if($val->key == 'buy_power_fee'){
                $buy_power_fee = $val->val;
            }
            if($val->key == 'buy_power_indirect_fee'){
                $buy_power_indirect_fee = $val->val;
            }
        }
        $power_fee = $info->all_capacity * $buy_power_fee;

        $insert_srt_record_arr = [];
        $insert_srt_record_arr[] = [

            'out_account' => $info->user_name,
            'out_phone' => $user_info->phone,
            'shift_account' =>  '自己',
            'shift_phone' => '自己',
            'amount' => $power_fee,
            'type_note' => '购机奖励',
            'type' => 'buy_power_fee',
        ];

        if($user_info->pid > 0){
            $parent = DB::table('user')->where('id',$user_info->pid)->select('username','phone')->first();

            $direct_power_fee = $power_fee * $buy_power_indirect_fee;
            $insert_srt_record_arr[] = [
                'out_account' => $parent->username,
                'out_phone' => $parent->phone,
                'shift_account' => $user_info->username,
                'shift_phone' => $user_info->phone,
                'amount' => $direct_power_fee,
                'type_note' => '推荐返佣',
                'type' => 'buy_power_indirect_fee',
            ];
            DB::table('user')->where('username', $parent->username)->increment('rebate',$direct_power_fee);
        }
        DB::table('record_srt')->insert($insert_srt_record_arr);
        DB::table('user')->where('username', $info->user_name)->increment('rebate',$power_fee);
        return s_msg('审核通过');

    }

    public static function get_level($performance){
        $config_level = Cache::get('config_level');
        $level_arr = array_column($config_level,'capacity');
        if(in_array($performance,$level_arr)){
            $key = array_keys($level_arr,$performance)[0];
        }else{
            array_push($level_arr,$performance);
            sort($level_arr);
            $key = array_keys($level_arr,$performance)[0]-1;
        }
        $level = $config_level[$key]->level;
        return $level;
    }


}
